<template>
  <div class="app-container">
    <div class="filter-container">
    
      <el-input
        v-model="listQuery.id"
        size="small"
        placeholder="ID"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-input
        v-model="listQuery.a2deptId"
        size="small"
        placeholder="a2dept_id"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-input
        v-model="listQuery.name"
        size="small"
        placeholder="name"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />


      <el-date-picker
        v-model="listQuery.createdate"
        type="daterange"
        value-format="yyyy-MM-dd"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="创建日期:开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        size="small"
        class="filter-item"
      />

      <el-input
        v-model="listQuery.createman"
        size="small"
        placeholder="创建人"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />

      <el-input
        v-model="listQuery.createmanId"
        size="small"
        placeholder="创建人ID"
        style="width: 200px; "
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" size="small" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" size="small" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <!-- 行展开，显示的详细信息 -->
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="ID" >
                <span>{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="a2dept_id" >
                <span>{{ props.row.a2deptId }}</span>
            </el-form-item>
            <el-form-item label="name" >
                <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="删除标志" >
                <span>{{ props.row.deleteflag }}</span>
            </el-form-item>
            <el-form-item label="创建日期" >
                <span>{{ props.row.createdate }}</span>
            </el-form-item>
            <el-form-item label="创建人" >
                <span>{{ props.row.createman }}</span>
            </el-form-item>
            <el-form-item label="修改日期" >
                <span>{{ props.row.modifydate }}</span>
            </el-form-item>
            <el-form-item label="修改人" >
                <span>{{ props.row.modifyman }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column label="ID" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="a2dept_id" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.a2deptId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="name" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="删除标志" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.deleteflag }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建日期" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.createdate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.createman }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改日期" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.modifydate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center" width="160">
        <template slot-scope="{row}">
          <span>{{ row.modifyman }}</span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column fixed="right" label="操作" align="center" min-width="230">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-popconfirm
            title="确认删除吗？"
            @onConfirm="handleDelete(row, $index)"
          >
            <el-button slot="reference" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <form-details ref="formDetails" :row="row" :isFromFather="true" @createResult="createResult" @updateResult="updateResult"/>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, deleteApi } from './api'
import waves from '@/directive/waves' // waves directive
import { parseTime, reorgQueryParams } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import FormDetails from './form-details.vue' // add form form dialog
// 从当前View的私有数据对象中取数据
import { pickerOptions, pickerOptionsSingleDate } from './data'

export default {
  name: 'A2deptList',

  components: { Pagination, FormDetails },
  directives: { waves },

  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      downloadLoading: false,
      pickerOptions: pickerOptions,
      pickerOptionsSingleDate: pickerOptionsSingleDate,
      row: {}
    }
  },

  created() {
    this.getList()
  },

  methods: {
    getList() {
      this.listLoading = true
      // 重组查询条件
      const params = Object.assign({}, this.listQuery)
      reorgQueryParams(params)
      // 查询
      fetchList(params).then(result => {
        this.list = result.map.rows
        this.total = result.map.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // 消除上次出现的验证信息
      this.$nextTick(() => {
        this.$refs['formDetails'].clearValidate()
        this.$refs['formDetails'].resetTemp()
      })
    },
    // 调用子组件操作数据
    createData() {
      this.$refs['formDetails'].createData()
    },
    // 子组件操作成功，回调此方法，关闭弹框、刷新
    createResult() {
      this.dialogFormVisible = false
      this.handleFilter()
    },

    handleUpdate(row) {
      this.row = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // 消除上次出现的验证信息
      this.$nextTick(() => {
        this.$refs['formDetails'].clearValidate()
      })
    },
    // 调用子组件操作数据
    updateData() {
      this.$refs['formDetails'].updateData()
    },
    // 子组件操作成功，回调此方法，关闭弹框、刷新
    updateResult() {
      this.dialogFormVisible = false
      this.getList()
    },

    handleDelete(row, index) {
      deleteApi({ id: '' + row.id }).then((result) => {
        if (result.success) {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+{key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 100px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 40%;
  }
</style>
